@{
    ViewData["Title"] = "销售发货订单管理";
    Layout = null;
}

<link rel="stylesheet" href="~/layui/css/layui.css">
<script src="~/libs/dayjs/dayjs.min.js"></script>

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">
            <h3>销售发货订单管理</h3>
        </div>
        <div class="layui-card-body">
            <!-- 搜索区域 -->
            <div class="layui-form layui-form-pane" style="margin-bottom: 15px;">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">订单编码</label>
                        <div class="layui-input-inline">
                            <input type="text" id="search-orderCode" placeholder="请输入订单编码" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">客户名称</label>
                        <div class="layui-input-inline">
                            <input type="text" id="search-customerName" placeholder="请输入客户名称" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">业务员</label>
                        <div class="layui-input-inline">
                            <input type="text" id="search-salesperson" placeholder="请输入业务员" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">订单状态</label>
                        <div class="layui-input-inline">
                            <select id="search-state" class="layui-input">
                                <option value="">全部状态</option>
                                <option value="0">草稿</option>
                                <option value="1">已确认</option>
                                <option value="2">审批中</option>
                                <option value="3">已审批</option>
                                <option value="4">已拒绝</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button class="layui-btn" id="btn-search">搜索</button>
                        <button class="layui-btn layui-btn-primary" id="btn-reset">重置</button>
                    </div>
                </div>
            </div>

            <!-- 工具栏 -->
            <div class="layui-btn-group" style="margin-bottom: 15px;">
                <button class="layui-btn" id="btn-add">新增</button>
                <button class="layui-btn layui-btn-danger" id="btn-delete">删除</button>
                <button class="layui-btn layui-btn-normal" id="btn-export">导出</button>
            </div>

            <!-- 数据表格 -->
            <table id="saleSendOrderTable" lay-filter="saleSendOrderTable"></table>
        </div>
    </div>
</div>

<script src="~/layui/layui.js"></script>

<!-- 状态模板 -->
<script type="text/html" id="orderStatusTpl">
    {{# if(d.state == 0) { }}
        <span class="layui-badge layui-bg-gray">草稿</span>
    {{# } else if(d.state == 1) { }}
        <span class="layui-badge layui-bg-blue">已确认</span>
    {{# } else if(d.state == 2) { }}
        <span class="layui-badge layui-bg-orange">审批中</span>
    {{# } else if(d.state == 3) { }}
        <span class="layui-badge layui-bg-green">已审批</span>
    {{# } else if(d.state == 4) { }}
        <span class="layui-badge layui-bg-red">已拒绝</span>
    {{# } }}
</script>

<!-- 操作栏模板 -->
<script type="text/html" id="tableBarTpl">
    {{# if(d.state == 0) { }}
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="confirm">确认</a>
    {{# } else if(d.state == 1) { }}
        <a class="layui-btn layui-btn-xs" lay-event="view">查看</a>
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="submit">提交审批</a>
    {{# } else if(d.state == 2) { }}
        <a class="layui-btn layui-btn-xs" lay-event="view">查看</a>
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="approve">通过</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="reject">拒绝</a>
    {{# } else if(d.state == 3) { }}
        <a class="layui-btn layui-btn-xs" lay-event="view">查看</a>
    {{# } else if(d.state == 4) { }}
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    {{# } }}
</script>

<script>
    layui.use(['table', 'form', 'layer', 'laydate'], function(){
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var laydate = layui.laydate;
        var $ = layui.$;

        // 初始化表格
        table.render({
            elem: '#saleSendOrderTable',
            url: '/SaleSendOrder/GetSaleSendOrders',
            cols: [[
                {type: 'checkbox', width: 50},
                {field: 'orderCode', title: '订单编码', width: 150, sort: true},
                {field: 'customerName', title: '客户名称', width: 180, sort: true},
                {field: 'orderDate', title: '订单日期', width: 120, sort: true, templet: function(d){
                    return dayjs(d.orderDate).format('YYYY-MM-DD');
                }},
                {field: 'deliveryType', title: '送货方式', width: 100},
                {field: 'warehouseCode', title: '仓库编码', width: 100},
                {field: 'salesperson', title: '业务员', width: 100},
                {field: 'baseCurrency', title: '币别', width: 80},
                {field: 'paymentMethod', title: '结算方式', width: 120},
                {field: 'totalAmount', title: '总金额', width: 120, sort: true},
                {field: 'totalQuantity', title: '总数量', width: 100},
                {field: 'state', title: '订单状态', width: 100, sort: true, templet: function(d){
                    return getStatusText(d.state);
                }},
                {field: 'createBy', title: '创建人', width: 100},
                {field: 'recordCreateTime', title: '创建时间', width: 160, sort: true, templet: function(d){
                    return dayjs(d.recordCreateTime).format('YYYY-MM-DD HH:mm:ss');
                }},
                {title: '操作', width: 250, templet: '#tableBarTpl', fixed: 'right'}
            ]],
            page: true,
            height: 'full-220'
        });

        // 表格操作栏事件
        table.on('tool(saleSendOrderTable)', function(obj){
            var data = obj.data;
            
            if(obj.event === 'edit'){
                // 编辑
                location.href = '/SaleSendOrder/Edit?id=' + data.id;
            } else if(obj.event === 'view'){
                // 查看
                location.href = '/SaleSendOrder/Edit?id=' + data.id + '&view=1';
            } else if(obj.event === 'del'){
                // 删除
                layer.confirm('确定删除该订单吗？', function(index){
                    $.ajax({
                        url: '/SaleSendOrder/DeleteSaleSendOrder',
                        type: 'POST',
                        data: {id: data.id},
                        success: function(res){
                            if(res.code === 0){
                                layer.msg('删除成功');
                                obj.del();
                            } else {
                                layer.msg(res.msg);
                            }
                        }
                    });
                    layer.close(index);
                });
            } else if(obj.event === 'confirm'){
                // 确认
                layer.confirm('确定确认该订单吗？确认后将无法修改！', function(index){
                    $.ajax({
                        url: '/SaleSendOrder/ConfirmOrder',
                        type: 'POST',
                        data: {id: data.id},
                        success: function(res){
                            if(res.code === 0){
                                layer.msg('确认成功');
                                table.reload('saleSendOrderTable');
                            } else {
                                layer.msg(res.msg);
                            }
                        }
                    });
                    layer.close(index);
                });
            } else if(obj.event === 'submit'){
                // 提交审批
                layer.confirm('确定提交审批吗？', function(index){
                    $.ajax({
                        url: '/SaleSendOrder/SubmitForApproval',
                        type: 'POST',
                        data: {id: data.id},
                        success: function(res){
                            if(res.code === 0){
                                layer.msg('提交审批成功');
                                table.reload('saleSendOrderTable');
                            } else {
                                layer.msg(res.msg);
                            }
                        }
                    });
                    layer.close(index);
                });
            } else if(obj.event === 'approve'){
                // 审批通过
                layer.confirm('确定审批通过吗？', function(index){
                    $.ajax({
                        url: '/SaleSendOrder/ApproveOrder',
                        type: 'POST',
                        data: {id: data.id},
                        success: function(res){
                            if(res.code === 0){
                                layer.msg('审批通过成功');
                                table.reload('saleSendOrderTable');
                            } else {
                                layer.msg(res.msg);
                            }
                        }
                    });
                    layer.close(index);
                });
            } else if(obj.event === 'reject'){
                // 审批拒绝
                layer.confirm('确定拒绝审批吗？', function(index){
                    $.ajax({
                        url: '/SaleSendOrder/RejectOrder',
                        type: 'POST',
                        data: {id: data.id},
                        success: function(res){
                            if(res.code === 0){
                                layer.msg('拒绝审批成功');
                                table.reload('saleSendOrderTable');
                            } else {
                                layer.msg(res.msg);
                            }
                        }
                    });
                    layer.close(index);
                });
            }
        });

        // 新增按钮事件
        $('#btn-add').on('click', function(){
            location.href = '/SaleSendOrder/Edit';
        });

        // 批量删除按钮事件
        $('#btn-delete').on('click', function(){
            var checkStatus = table.checkStatus('saleSendOrderTable');
            var data = checkStatus.data;
            if(data.length === 0){
                layer.msg('请选择要删除的数据');
                return;
            }

            var canDelete = true;
            var ids = [];
            $.each(data, function(index, item){
                if(item.state !== 0 && item.state !== 4){
                    canDelete = false;
                    return false;
                }
                ids.push(item.id);
            });

            if(!canDelete){
                layer.msg('只能删除草稿或已拒绝状态的订单');
                return;
            }

            layer.confirm('确定删除选中的 ' + data.length + ' 条数据吗？', function(index){
                var loadIndex = layer.load(2);
                var count = 0;
                var errorMsg = '';

                function deleteNext(){
                    if(count >= ids.length){
                        layer.close(loadIndex);
                        if(errorMsg){
                            layer.alert(errorMsg);
                        } else {
                            layer.msg('删除成功');
                            table.reload('saleSendOrderTable');
                        }
                        return;
                    }

                    $.ajax({
                        url: '/SaleSendOrder/DeleteSaleSendOrder',
                        type: 'POST',
                        data: {id: ids[count]},
                        success: function(res){
                            if(res.code !== 0){
                                errorMsg += '订单ID ' + ids[count] + ' 删除失败: ' + res.msg + '<br>';
                            }
                            count++;
                            deleteNext();
                        },
                        error: function(){
                            errorMsg += '订单ID ' + ids[count] + ' 删除失败: 网络错误<br>';
                            count++;
                            deleteNext();
                        }
                    });
                }

                deleteNext();
                layer.close(index);
            });
        });

        // 导出按钮事件
        $('#btn-export').on('click', function(){
            var orderCode = $('#search-orderCode').val();
            var customerName = $('#search-customerName').val();
            var salesperson = $('#search-salesperson').val();
            var state = $('#search-state').val();

            var params = '?';
            if(orderCode) params += 'OrderCode=' + encodeURIComponent(orderCode) + '&';
            if(customerName) params += 'CustomerName=' + encodeURIComponent(customerName) + '&';
            if(salesperson) params += 'Salesperson=' + encodeURIComponent(salesperson) + '&';
            if(state !== '') params += 'State=' + state + '&';

            // 移除末尾的 & 或 ?
            params = params.replace(/[&?]$/, '');

            window.location.href = '/SaleSendOrder/ExportOrders' + params;
        });

        // 搜索按钮事件
        $('#btn-search').on('click', function(){
            var orderCode = $('#search-orderCode').val();
            var customerName = $('#search-customerName').val();
            var salesperson = $('#search-salesperson').val();
            var state = $('#search-state').val();

            var where = {};
            if(orderCode) where.orderCode = orderCode;
            if(customerName) where.customerName = customerName;
            if(salesperson) where.salesperson = salesperson;
            if(state !== '') where.state = parseInt(state);

            table.reload('saleSendOrderTable', {
                where: where,
                page: {curr: 1}
            });
        });

        // 重置按钮事件
        $('#btn-reset').on('click', function(){
            $('#search-orderCode').val('');
            $('#search-customerName').val('');
            $('#search-salesperson').val('');
            $('#search-state').val('');
            form.render('select');

            table.reload('saleSendOrderTable', {
                where: {},
                page: {curr: 1}
            });
        });
    });

    function getStatusText(status){
        switch(status){
            case 0: return '草稿';
            case 1: return '已确认';
            case 2: return '审批中';
            case 3: return '已审批';
            case 4: return '已拒绝';
            default: return '未知';
        }
    }
</script> 